<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-page-header content="发布商品" style="padding-bottom: 50px" @back="goBack" />
      <el-form ref="form" :model="form" label-width="120px" label-position="right" label-suffix="：" class="form_style" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="form.goods_name" style="width: 400px" placeholder="商品名称" clearable />
            </el-form-item>
            <el-form-item label="商品分类" prop="category_id">
              <el-select v-model="form.category_id" placeholder="请选择商品分类" style="width: 200px" @change="changeClass">
                <el-option
                  v-for="item in goodsClass"
                  :key="item.category_id"
                  :label="item.category_name"
                  :value="item.category_id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="form.goods_price" clearable style="width: 200px; margin-right: 30px" placeholder="商品价格" />
            </el-form-item>
            <el-form-item label="商品优惠价格" prop="goods_preferential">
              <el-input v-model="form.goods_preferential" style="width: 200px" placeholder="商品优惠价格" clearable />
            </el-form-item>
            <el-form-item label="商品描述" prop="goods_desc">
              <el-input v-model="form.goods_desc" type="textarea" :rows="3" style="width: 400px" placeholder="商品描述" />
            </el-form-item>
            <el-form-item label="商品主图" prop="goods_img">
              <new-upload
                :file_source="goods_file_source"
                :upload-type="3"
                :format="'.jpg,.jpeg,.png,.JPG,.JPEG,.PNG'"
                :format-txt="'最多上传1张,支持格式：.jpg,.jpeg,.png,.JPG,.JPEG,.PNG'"
                :limit-num="1"
                @reUpload="getUpladImg"
                :fileArr="form.goods_img"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品规格" prop="specification_ids" align="left">
              <div>
                <span>已选:</span>
                <el-tag v-for="(item, index) in form.specification_ids" :key="index" size="medium" style="margin: 2px 3px">
                  {{ item.specification_name }}
                </el-tag>
                <!-- <span v-for="(item, index) in form.specification_ids" :key="index">{{ item.specification_name }}</span> -->
              </div>
              <el-table :data="specification_list" border v-loading="listLoading" height="450px">
                <el-table-column prop="id" label="勾选" width="50">
                  <template #default="{ row, $index }">
                    <el-checkbox v-model="specification_list[$index].select" @change="changeVal($event, $index)"></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column prop="specification_name" label="规格名称" align="center" width="100" />
                <el-table-column prop="specification_value" label="规格值" align="center">
                  <template #default="{ row }">
                    <el-tag v-for="(item, index) in row.specification_value" :key="index" type="warning" size="medium">
                      {{ deleteSymbol(item) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="footer-btn">
        <el-button type="primary" style="margin-right: 10px" @click="Submit" size="medium">提交</el-button>
        <el-button @click="goBack" size="medium">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
  import NewUpload from '@/components/NewUpload'
  import { get_goods_detail, get_goods_specification, edit_goods } from '@/api/goods'
  export default {
    components: { NewUpload },
    data() {
      return {
        listLoading: false,
        form: {
          store_imgs: [],
          specification_ids: [],
        },
        goods_file_source: 'goods_imgs',
        checkedVal: '',
        specification_list: [],
        goodsClass: JSON.parse(localStorage.getItem('category_list')) || [],
        rules: {
          goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
          goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
          goods_img: [{ required: true, message: '请选择商品主图', trigger: 'change' }],
          category_id: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
          specification_ids: [{ required: true, message: '请选择商品规格', trigger: 'blur' }],
        },
      }
    },
    mounted() {
      this.get_detail()
    },
    methods: {
      get_detail() {
        get_goods_detail({ id: this.$route.query.id }).then(({ data }) => {
          console.log('data: ', data)
          this.form = data
          this.form.goods_img = [this.form.goods_img]
          this.form.specification_ids = data.specification_ids.split(',')
          this.get_goods_specification()
        })
      },
      async get_goods_specification() {
        this.listLoading = true
        await get_goods_specification().then(({ data }) => {
          // this.specification_list = data.list
          let select_list = []
          data.list.forEach((item) => {
            item.specification_value = item.specification_value.split(',')
            this.form.specification_ids.forEach((id) => {
              if (item.specification_id == id) {
                item.select = true
                select_list.push(item)
              }
            })
          })
          this.form.specification_ids = select_list
          this.specification_list = data.list
          console.log('this.specification_list: ', this.specification_list)
        })
        this.listLoading = false
      },
      // 根据商品分类设置图片上传的地址
      changeClass(val) {
        let url = {
          0: 'new_goods',
          1: 'breakfast',
          2: 'tea',
          3: 'xm_coffee',
          4: 'ms_coffee',
          5: 'tea',
          6: 'tea',
          7: 'tea',
          8: 'milk_tea',
        }
        this.goods_file_source = 'goods_imgs/' + url[val]
        console.log(' this.goods_file_source : ', this.goods_file_source)
      },
      Submit() {
        console.log(this.form)
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$confirm('确认修改商品操作?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(async () => {
              await edit_goods(this.form).then((data) => {
                if (data.code == 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                  })
                  this.$router.push('/goods/list')
                } else {
                  this.$message.error(data.msg)
                }
              })
            })
          } else {
            return false
          }
        })
      },
      goBack() {
        this.$router.push('/goods/list')
      },
      deleteSymbol(val) {
        if (!val.includes('|')) return val
        return val.replace(/\|/g, '￥')
      },
      changeVal(val, index) {
        this.form.specification_ids = this.specification_list.filter((item) => {
          return item.select
        })
        console.log('this.form.specification_ids: ', this.form.specification_ids)
      },
      getUpladImg(file_list) {
        console.log('file_list: ', file_list)
        this.form.goods_img = file_list
      },
    },
  }
</script>

<style scoped>
  .tips {
    margin-left: 120px;
    margin-top: 0;
    margin-bottom: 20px;
    font-size: 14px;
    color: rgb(235, 44, 44);
  }
  .footer-btn {
    text-align: center;
    margin-top: 50px;
  }
  .specification-btn {
    display: inline-block;
    padding-left: 20px;
    margin-bottom: 10px;
  }
</style>
